package cc.eddic.practice.spring.webapi;

import cc.eddic.practice.spring.dto.StudentAddRequest;
import cc.eddic.practice.spring.dto.StudentResponse;
import cc.eddic.practice.spring.repository.StudentRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/students")
public class StudentRestController {

    private final StudentRepository repository;

    public StudentRestController(StudentRepository repository){
        this.repository=repository;
    }

    @PostMapping
    public HttpEntity<?> add(@RequestBody final StudentAddRequest model){
        val student=repository.save(model.as());//as()创建新的student对象
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(student.getId()).toUri()).build();
    }

    @GetMapping("/{id}")
    public HttpEntity<StudentResponse> get(@PathVariable("id") final long id){
        if(log.isDebugEnabled()) log.debug("id = {}",id);
        val student = repository.findById(id).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(StudentResponse.from(student));
    }

    @DeleteMapping("/{id}")
    public HttpEntity<?> del(@PathVariable("id") final long id){
        repository.deleteById(id);
        return ResponseEntity.noContent().build();
    }

    @GetMapping
    public HttpEntity<Page<StudentResponse>> getAll(@PageableDefault(size = 1,page = 0) Pageable pageable){
        log.debug("size={},page={}",pageable.getPageSize(),pageable.getPageNumber());
//        val students=repository.findAll().stream().map(StudentResponse::from).collect(Collectors.toList());
//        return ResponseEntity.ok(students);
        return ResponseEntity.ok(repository.findAll(pageable).map(StudentResponse::from));
    }

}
